import React, { useEffect, useState, useReducer, useRef } from 'react';
import { history, useSelector, Link } from 'umi';
import Header from '@/components/Header/Header';
import Png_Logo from '@/assets/images/logo.png';
import { ActionSheet, Message } from '@/design';
import { checkField, isEmpty, encryptMd5 } from '@/utils/common';
import { queryCheckPhoneAuth, queryUserLogin, queryUserRegister } from '@/services/user';
import GetCaptcha from '@/components/GetCaptcha/GetCaptcha';
import styles from './user.less';

export default function (props: any) {

  let unmount = false;
  const spinning = useRef(false);

  const initialState = {
    phoneAreaCode: '886',
    isPassLogin: true,
    hasRegister: true,
    formData: {},
    canSubmit: false,
    canGetCaptcha: false,
    readRule: true,
    showRule: false,
  }
  const reducer = (state: any, action: any) => {
    switch (action.type) {
      case 'saveAreaCode': return { ...state, phoneAreaCode: action.payload };
      case 'savePhone': return { ...state, phone: action.payload };
      case 'saveIsPassLogin': return { ...state, isPassLogin: action.payload };
      case 'saveHasRegister': return { ...state, hasRegister: action.payload };
      case 'saveFormData': return { ...state, formData: { ...state.formData, ...action.payload } };
      case 'saveCanSubmit': return { ...state, canSubmit: action.payload };
      case 'saveCanGetCaptcha': return { ...state, canGetCaptcha: action.payload };
      case 'saveReadRule': return { ...state, readRule: action.payload };
      case 'saveShowRule': return { ...state, showRule: action.payload };
      default: throw new Error();
    }
  }
  const [state, dispatch] = useReducer(reducer, initialState);

  const [rememberPwd, setRememberPwd] = useState(true);
  const [preInfo, setPreInfo] = useState({});
  const areaCodesTips: any = {
    T86: '請填寫11位有效的手機號碼',
    T886: '請填寫有效的手機號碼10碼',
    T852: '請填寫8位有效的手機號碼',
  };

  /** 選擇區號 */
  const handleChangeArea = () => {
    let areaSelect = ActionSheet.show({
      list: ['86', '886', '852'],
      maskClose: true,
      renderRow: (item) => (<span>{item}</span>),
      onSelect: (phoneAreaCode) => {
        areaSelect.hide();
        console.log('你选的是', phoneAreaCode)
        dispatch({
          type: 'saveAreaCode',
          payload: phoneAreaCode
        });
      }
    })
  }

  /* 表单数据监听 */
  const handleFormChange = (event: any) => {
    const { name, value } = event.target;
    let newObj: any = {};
    newObj[name] = value;
    if (name === 'mobileNumber') {
      newObj['passwd'] = ''
    }
    setPreInfo({});
    dispatch({ type: 'saveFormData', payload: newObj });
  }

  /* 检查手机号是否已注册 */
  const handlePhoneBlur = async () => {
    const { phoneAreaCode, formData: { mobileNumber = '' } } = state;
    if (mobileNumber.length < 7) return false;
    let checkPhone = checkField(`phone_${phoneAreaCode}`, mobileNumber);
    if (checkPhone) {
      Message.error(checkPhone);
      return false
    };
    let result = await queryCheckPhoneAuth({ phoneAreaCode: `+${phoneAreaCode}`, mobileNumber });
    if (!result) return false;
    dispatch({
      type: 'saveHasRegister',
      payload: result.data === 'Y'
    });
    dispatch({
      type: 'saveIsPassLogin',
      payload: result.data === 'Y' ? state.isPassLogin : false
    });
    dispatch({ type: 'saveCanGetCaptcha', payload: true });
  }
  /* 号码框聚焦时禁用获取验证码 */
  const handlePhoneFocus = () => {
    dispatch({ type: 'saveCanGetCaptcha', payload: false });
  }

  /* 验证表单是否可以提交 */
  const checkCanSubmit = () => {
    const {
      hasRegister,
      isPassLogin,
      formData: { mobileNumber = '', smsCode = '', passwd = '' }
    } = state;
    let msg = '';
    if (isEmpty(mobileNumber)) {
      msg = '手機號不可為空'
    }
    if (isPassLogin) {
      // msg = checkField(`phone_${phoneAreaCode}`, mobileNumber);
      msg = msg === '' ? checkField(`password`, passwd) : msg;
    } else {
      if (hasRegister) {
        // msg = checkField(`phone_${phoneAreaCode}`, mobileNumber);
        msg = msg === '' ? checkField(`captcha`, smsCode) : msg;
      } else {
        // msg = checkField(`phone_${phoneAreaCode}`, mobileNumber);
        msg = msg === '' ? checkField(`captcha`, smsCode) : msg;
        msg = msg === '' ? checkField(`password`, passwd) : msg;
        if (!state.readRule) {
          msg = '請閱讀並同意協議後，才能成為ume會員!'
        }
        // console.log(hasRegister)
      }
    }
    // console.log(isPassLogin,msg)
    return msg;
  }

  /* 提交表单 */
  const handleFormSubmit = async () => {
    let msg = checkCanSubmit();
    if (!isEmpty(msg)) {
      Message.error(msg);
      return;
    }
    const {
      phoneAreaCode,
      hasRegister,
      isPassLogin,
      formData: { mobileNumber = '', smsCode = '', passwd = '' }
    } = state;
    let params = { phoneAreaCode: `+${phoneAreaCode}`, mobileNumber, smsCode, passwd, registerSource: 'fnbWeb', regMerMember: '1' };
    params['passwd'] = encryptMd5(passwd);
    if (spinning.current) {
      return false;
    }
    if (!isEmpty(preInfo)) {
      params = { ...params, ...preInfo }
    }
    let result:any = false;
    if (isPassLogin) {
      /* 账号密码登录 */
      delete params['smsCode'];
    } else {
      /* 登录注册合一 */
      if (hasRegister) {
        /* 已注册 */
        delete params['passwd'];
      }
    }
    spinning.current = true;
    if (isPassLogin) {
      result = await queryUserLogin(params);
    } else {
      if (hasRegister) {
        result = await queryUserLogin(params);
      } else {
        result = await queryUserRegister(params);
      }
    }
    spinning.current = false;
    if (!result) return false;
    if (isPassLogin && rememberPwd) {
      // console.log('更新密碼', params['passwd'])
      let preLoginInfo: any = { phoneAreaCode, mobileNumber, passwd: params['passwd'] };
      preLoginInfo = window.btoa(unescape(encodeURIComponent(JSON.stringify(preLoginInfo))));
      localStorage.setItem('l_i', preLoginInfo);
    } else {
      localStorage.removeItem('l_i');
    }
    localStorage.removeItem('captchaTimed');
    localStorage.setItem('userInfo', JSON.stringify(result.data  || {}));
    localStorage.setItem('TOKEN', result.data.token)
    Message.success(hasRegister ? '登入成功！' : '恭喜您，註冊成功！');
    console.log('historyhistory', history)
    if (history.length < 2) {
      history.replace('/home');
    } else {
      history.goBack();
    }
  }

  console.log('formdata', state)

  return <>
    <div className={styles.login_wrap}>
      <Header hasBack leftExtra="返回快捷登入"></Header>
      <img className={styles.users_login_logo} src={Png_Logo} />
      <form className={styles.users_login_form}>
        {/* 账号 */}
        <div className={styles.form_line}>
          <button className={styles.area_code} type="button" onClick={handleChangeArea}>{state.phoneAreaCode}</button>
          <input
            className={styles.form_input}
            maxLength={11}
            type="text"
            placeholder={areaCodesTips[`T${state.phoneAreaCode}`]}
            name="mobileNumber"
            onChange={handleFormChange}
            onBlur={handlePhoneBlur}
            onFocus={handlePhoneFocus}
            defaultValue={state.formData['mobileNumber'] || ''}
          />
        </div>
        {/* 验证码 */}
        {!state.isPassLogin && <div className={styles.form_line}>
          <input className={styles.form_input} maxLength={6} type="text" placeholder="輸入短信驗證碼" name="smsCode" onChange={handleFormChange} />
          <GetCaptcha
            className={styles.form_captcha}
            // disabled={!state.canGetCaptcha}
            action={state.hasRegister ? 'login' : 'register'}
            mobileNumber={state.formData.mobileNumber}
            phoneAreaCode={state.phoneAreaCode} />
        </div>}
        {/* 设置密码 */}
        {(!state.isPassLogin && !state.hasRegister) && <div className={styles.form_line}>
          <input className={styles.form_input} maxLength={16} type="password" placeholder="設置登入密碼" name="passwd" onChange={handleFormChange} />
        </div>}
        {!state.isPassLogin && <div className={styles.form_tips}>
          {!state.hasRegister ? '密碼由6~16字母、數字組成，不限大小寫' : ''}
        </div>}
        {/* 登录密码 */}
        {state.isPassLogin && <div className={styles.form_line}>
          <input className={styles.form_input} maxLength={16} type="password" value={state.formData['passwd']} placeholder="輸入登入密碼" name="passwd" onChange={handleFormChange} />
        </div>}
        {/* 忘记密码 */}
        <div className={`${styles.forget_wrap} ${styles.login_action}`}>
          {state.isPassLogin ? <div className={styles.checkbox}>
            <input type="checkbox" id='option' />
            <label htmlFor="option">記住密碼
              <svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M13 50.986L37.334 75 88 25" strokeWidth="6" stroke="#02ADDA" fill="none" fillRule="evenodd" strokeDasharray="150" strokeDashoffset="150" /></svg>
            </label>
          </div> : <div></div>}
          <Link to="/forget" className={styles.form_forget}>忘記密碼？</Link>
        </div>

        {/* {state.isPassLogin && <div className={styles.login_action}>
          <CheckBox pure checked={rememberPwd} onChange={handleRememberPwd}>記住密碼</CheckBox>
          <Link to="/forget" className={styles.form_forget}>忘記密碼？</Link>
        </div>} */}
        {/* <div className={styles.error_tips}>{}</div> */}
        {/* 提交按钮 */}
        <button className={styles.form_submit} type="button" onClick={handleFormSubmit}>
          {state.isPassLogin ? '登 入' : '註冊 / 登入'}
        </button>
        {/* 方式切换 */}
        <button className={styles.users_login_method} type="button">
          {state.isPassLogin ? '使用短信驗證碼登入/註冊' : '使用賬號密碼登入'}
        </button>
      </form>
    </div>
  </>
}